package com.cy.store11.controller;

import com.cy.store11.controller.ex.*;
import com.cy.store11.controller.ex.FileEmptyException;
import com.cy.store11.entity.User;
import com.cy.store11.service.IUserService;
import com.cy.store11.service.ex.InsertException;
import com.cy.store11.service.ex.UsernameDuplicatedException;
import com.cy.store11.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@RestController
@RequestMapping(value = "users")
public class UserController extends BaseController {

    @Value("${upload.path}")
    private String filePath;

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "reg")
    public JsonResult<Void> reg(User user) {
        userService.reg(user);
        return new JsonResult<>(OK);
        //创建响应结果对象
//        JsonResult<Void> result = new JsonResult<>();
//        try {
//            userService.reg(user);
//            result.setState(200);
//            result.setMessage("用户注册成功");
//        } catch (UsernameDuplicatedException e) {
//            result.setState(4000);
//            result.setMessage("用户名被占用");
//        } catch (InsertException e) {
//            result.setState(5000);
//            result.setMessage("注册时产生未知异常");
//        }
//        return result;
    }
    @RequestMapping(value = "login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username,password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        //打印
        System.out.println(getuidFromSession(session));
        System.out.println(getUsernameFromSession(session));
        return new JsonResult<User>(OK,data);
    }

    @RequestMapping(value = "change_password")
    public JsonResult<Void> changePassword(String oldPassword,String newPassword,HttpSession session){

        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping(value = "get_by_uid")
    public JsonResult<User> getByUid(HttpSession session){
        User data = userService.getByUid(getuidFromSession(session));
        return  new JsonResult<>(OK,data);
    }

    @RequestMapping(value = "change_Info")
    public JsonResult<Void> changeInfo(User user,HttpSession session)
    {
        //user对象有四部分数据，username,phone,email,gender
        //uid数据需要再次封装到user对象中
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    //设置上传文件的最大值
    public static final int AVATAR_MAX_SIZE = 10*1024*1024;

    //限制上传文件的类型
    public static final List<String> AVATAR_TYPE =
                                        new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpg");
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }

    /**
     * MultipartFile接口是SpringMVC提供一个接口，这个接口为我们包装了
     * 获取文件类型的数据（任何类型的file都可以接收），SpringBoot它整合了
     * @param session
     * @param file
     * @return
     */
    @RequestMapping(value = "change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file)
    {
        //判断文件是否为null
        if(file.isEmpty())
        {
            throw new FileEmptyException("文件为空");
        }
        if(file.getSize()>AVATAR_MAX_SIZE)
        {
            throw new FileSizeException("文件超过限制");
        }
        //判断文件的类型是否是我们规定的后缀类型
        String contentType = file.getContentType();
        //如果集合包含某个元素则返回true
        if(!AVATAR_TYPE.contains(contentType))
        {
            throw new FileTypeException("文件类型不支持");
        }
        //上传的文件.../upload/文件.png
        String parent =
                session.getServletContext().getRealPath("upload2");
//        parent = ClassUtils.getDefaultClassLoader().getResource("static/upload2").getPath();
        //File对象指向这个路径，File是否存在
        File dir = new File(filePath);
        if(!dir.exists()) //检测目录是否存在
        {
            dir.mkdirs(); //创建当前的目录
        }
        //获取到这个文件名称,UUID工具生成一个新的字符串作为文件名
        //avatar01.png
        String originalFilename = file.getOriginalFilename();
        System.out.printf("OriginalFilename="+originalFilename);
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest = new File(dir,filename);//是一个空文件

        try{
            file.transferTo(dest);//将file文件中的数据写入到dest文件
        }catch (FileStateException e)
        {
            throw new FileStateException("文件状态异常");
        }
        catch (IOException e){
            throw new FileUploadException("文件读写异常");
        }
        Integer uid =getuidFromSession(session);
        String username = getUsernameFromSession(session);
        //返回头像的路径
        String avatar = "/images2/"+filename;
        userService.changeAvatar(uid,avatar,username);
        //返回给前端
        return  new JsonResult<>(OK,avatar);

    }


}

